package com.cmc.cloud.cmclink.doc.rpcservice.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.cmc.cloud.cmclink.bdt.api.base.VesselDataApi;
import com.cmc.cloud.cmclink.bdt.api.base.dto.req.VesselNameListByCodeReqDTO;
import com.cmc.cloud.cmclink.bdt.api.base.dto.req.VesselNameReqDTO;
import com.cmc.cloud.cmclink.bdt.api.base.dto.resp.VesselNameDataRespDTO;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.ApiErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.entity.BlnoDO;
import com.cmc.cloud.cmclink.doc.rpcservice.VesselTransferService;
import com.cmc.cloud.cmclink.svl.api.base.ScheduleApi;
import com.cmc.cloud.cmclink.svl.api.base.enums.SystemEnums;
import com.cmc.cloud.cmclink.svl.api.base.req.VoyQueryReqDTO;
import com.cmc.cloud.cmclink.svl.api.base.resp.VoyQueryRespDTO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 港口基础数据转换
 *
 * @author dev89
 * @date 2025/07/18 09:07
 **/
@Service
@Validated
@Slf4j
public class VesselTransferServiceImpl implements VesselTransferService {

    private static final Long INTERVAL_MONTH = 6L;
    private static final String ETD_DATE_TYPE = "ETD";
    @Resource
    private VesselDataApi vesselApi;
    @Resource
    private ScheduleApi scheduledApi;

    @Override
    public List<VesselNameDataRespDTO> getVesselNamesData(String vesselCode) {
        CommonResult<List<VesselNameDataRespDTO>> commonResult;
        try {
            VesselNameReqDTO vesselNameReq = new VesselNameReqDTO();
            vesselNameReq.setVesselCode(vesselCode);
            commonResult = vesselApi.list(vesselNameReq);
        } catch (Exception e) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.VESSEL_GET_NAME_DATA_FAILED);
        }
        if (commonResult == null || CollectionUtil.isEmpty(commonResult.getData())) {
            log.error("港口基础数据返回空");
            return Collections.emptyList();
        } else {
            return commonResult.getData();
        }
    }

    @Override
    public String getEtdByVoyage(BlnoDO blnoDO, String laneCode) {
        return getVoyByVoyage(blnoDO, laneCode).getPtu();
    }

    @Override
    public VoyQueryRespDTO getVoyByVoyage(BlnoDO blnoDO, String laneCode) {
        VoyQueryReqDTO voy = new VoyQueryReqDTO();
        LocalDate now = LocalDate.now();
        voy.setExVoy(blnoDO.getBkgVoyage());
        voy.setStartDate(String.valueOf(now.minusMonths(INTERVAL_MONTH)));
        voy.setEndDate(String.valueOf(now.plusMonths(INTERVAL_MONTH)));
        voy.setSystemNumber(SystemEnums.DOC.getSystemNumber());
        voy.setPortCode(blnoDO.getPorCode());
        List<String> vesselCodeList = new ArrayList<>();
        vesselCodeList.add(blnoDO.getBkgVesselCode());
        voy.setVesselCode(vesselCodeList);
        voy.setDateType(ETD_DATE_TYPE);
        voy.setLaneCode(laneCode);

        log.info("ptu calculate start:{}, blnoId:{}", LocalDateTime.now(), blnoDO.getId());
        CommonResult<List<VoyQueryRespDTO>> commonResult = scheduledApi.listByCondition(voy);
        log.info("ptu calculate end:{}, blnoId:{}", LocalDateTime.now(), blnoDO.getId());
        List<VoyQueryRespDTO> voyQueryRespDTOList = commonResult.getCheckedData();
        return voyQueryRespDTOList.get(0);
    }

    @Override
    public Map<String, VesselNameDataRespDTO> getVesselDataByCodes(List<String> vesselCodeList) {
        // 通过船名编码 获取船的详细信息
        VesselNameListByCodeReqDTO codeReq = new VesselNameListByCodeReqDTO();
        codeReq.setVesselCodeList(vesselCodeList);
        CommonResult<List<VesselNameDataRespDTO>> commonResult;
        try {
            commonResult = vesselApi.listByCodeList(codeReq);
        } catch (Exception e) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.VESSEL_GET_BY_CODES_EXCEPTION);
        }
        if (commonResult == null || CollectionUtil.isEmpty(commonResult.getData())) {
            log.error("通过vessel_code获取船名为空");
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.VESSEL_GET_BY_CODES_EMPTY);
        }
        return commonResult.getData().stream().filter(Objects::nonNull)
            .collect(Collectors.toMap(VesselNameDataRespDTO::getVesselCode, // key mapper
                respDTO -> respDTO, // value mapper
                (existing, replacement) -> existing // 重复key处理：保留已存在的
            ));
    }
}
